function Browser() {

	var ua, s, i;

	this.isIE    = false;
  	this.isNS    = false;
  	this.version = null;

	ua = navigator.userAgent;

  	s = "MSIE";
  	if ((i = ua.indexOf(s)) >= 0) {
    	this.isIE = true;
    	this.version = parseFloat(ua.substr(i + s.length));
    	return;
    }

  	s = "Netscape6/";
  	if ((i = ua.indexOf(s)) >= 0) {
    	this.isNS = true;
	    this.version = parseFloat(ua.substr(i + s.length));
	    return;
    }

  	// Treat any other "Gecko" browser as NS 6.1.

	s = "Gecko";
    if ((i = ua.indexOf(s)) >= 0) {
  		this.isNS = true;
    	this.version = 6.1;
    	return;
  	}
}

var browser = new Browser();

var heights = new Array();
var intervals = new Array();
var newWsLink = "";
var newWsForm = "<input type='text'>&nbsp;<input type='button' value=' Adicionar ' onclick='addWorkspace();'>&nbsp;<a href='javascript:cancelNewWorkspace();'>Cancelar</a>";

//var wsLink = "<table width='100%' cellspacing='0' cellpadding='0'><tr><td><a class='activews' href=\"javascript:rename('#id')\">#nome</a></td><td align='right'>&nbsp;<a class='activews' href=\"javascript:deleteWorkspace('#id');\" style='color:red;'>X</a></td></tr></table>";

var wsLink = "<table width='100%' cellspacing='0' cellpadding='0'>" +
			 "<tr>" +
			 "<td><a id='ws_class' class='workspace_tab_active_text_#color' href=\"javascript:rename('#id')\">#nome</a></td>" + 
			 "<td align='right'><a id='ws_class' class='workspace_tab_active_text_#color' href=\"javascript:deleteWorkspace('#id');\">X</a></td>" + 
			 "</tr>" + 
			 "</table>"

var renameWsForm = "<table width='100%' cellspacing='0' cellpadding='0'><tr><td>" +
				   "<input type='text' value='#nome' size='10' maxlenght='20'></td><td align='right'>" +
				   "<a class='workspace_tab_active_text_#color' href=\"javascript:renameWorkspace('#id');\">V</a>" +
				   "</td></tr></table>";

var ownerId;
var globalZIndex = 0;

function objectEval(text)
{
    // eval() breaks when we use it to get an object using the { a:42, b:'x' }
    // syntax because it thinks that { and } surround a block and not an object
    // So we wrap it in an array and extract the first element to get around
    // this.
    // The regex = [start of line][whitespace]{[stuff]}[whitespace][end of line]
    text = text.replace(/\n/g, ' ');
    text = text.replace(/\r/g, ' ');
    if (text.match(/^\s*\{.*\}\s*$/))
    {
      	text = '[' + text + '][0]';
    }
    return eval(text);
}
  
function removeBlock(id) {
  	var el = document.getElementById('block_' + id);  	
	el.style.display = 'none';
  	AjaxFunctions.removeBlock(id);
}

function setHeight(id, h) {
	heights["" + id] = h;
}

function getHeight(id) {
	return heights["" + id];
}

function isEmpty(node) {
	if (node.innerHTML == null || node.childNodes == null || node.childNodes.length == 0) {
		return true;
	} 
	if (trimString(node.innerHTML) == '') {
		return true;
	}
	return false;
}

function toggle(id) {
	var block = document.getElementById('block_' + id);
	var title = document.getElementById('block_header_' + id);
	var content = document.getElementById('block_content_' + id);
	var footer = document.getElementById('block_footer_' + id);		

	if(block.style.height == '26px') {
		content.style.display = '';
		footer.style.display = '';
		block.style.height = getHeight(id);
		
		var contentDiv = document.getElementById('block_content_' + id)
		if (isEmpty(contentDiv)) {
			/**
	 		* SKUBS AJAX
			AjaxFunctions.toggleBlock(id, function() {
				refresh(id)
			});
			*/
		} else {
			/**
			* SKUBS AJAX
		  	AjaxFunctions.toggleBlock(id);
		  	*/
		}
	} else {
		content.style.display = 'none';
		footer.style.display = 'none';
		setHeight(id, block.style.height);
		block.style.height = '26px';
		/**
	 	* SKUBS AJAX
		AjaxFunctions.toggleBlock(id);
	 	*/		
	}

}

function style(id) {
	var target = document.getElementById('style_config_' + id);
	var other = document.getElementById('custom_config_' + id);
	if(other != null && other.style.display == '') {
		other.style.display = 'none';
	}	
	if(target.style.display == 'none') {
		target.style.display = '';
		target.style.zIndex = '10000';
	} else {
		target.style.display = 'none';
	}
}

function applyClassname(object, oldColor, newColor){
	if (object != null) {	
		object.className = object.className.replace(oldColor, newColor);
	}
}

function changeClass(id) {
	var select = document.getElementById('select_style_' + id);	
	var newColor = select.options[select.selectedIndex].value;	
	oldColor = document.getElementById('block_color_' + id).className

	var blockStyleCounter = document.getElementById('block_style_number_' + id).className;
	var blockCustomCounter = document.getElementById('block_custom_number_' + id).className;
	var blockCounter = document.getElementById('block_number_' + id).className;

	for (i=1; i<=blockStyleCounter; i++) {
		applyClassname (document.getElementById('block_style_' + i + '_' + id), oldColor, newColor);
	}
	for (i=1; i<=blockCustomCounter; i++) {
		applyClassname (document.getElementById('block_custom_' + i + '_' + id), oldColor, newColor);
	}
	for (i=1; i<=blockCounter; i++) {
		applyClassname (document.getElementById('block_' + i + '_' + id), oldColor, newColor);
	}
	// Aplicar nos locais comuns de todo bloco gen�rico
	applyClassname (document.getElementById('block_' + id), oldColor, newColor);
	applyClassname (document.getElementById('print_link_' + id), oldColor, newColor);
	applyClassname (document.getElementById('custom_link_' + id), oldColor, newColor);
	applyClassname (document.getElementById('style_link_' + id), oldColor, newColor);
	applyClassname (document.getElementById('minmax_link_' + id), oldColor, newColor);
	applyClassname (document.getElementById('close_link_' + id), oldColor, newColor);
	applyClassname (document.getElementById('content_div_' + id), oldColor, newColor);
	applyClassname (document.getElementById('resize_link_' + id), oldColor, newColor);
	
	if(!findClass(newColor)) {
		addClass(newColor);
	}
	style(id);
	AjaxFunctions.updateStyle(id, newColor);
	var d = document.getElementById('block_color_' + id);
	d.className=newColor;
}

function changeWorkspaceClass() {
	var select = document.getElementById('select_style_header');
	var newColor = select.options[select.selectedIndex].value;	
	idActive = document.getElementById('active_workspace_id').className;
	oldColor = document.getElementById('active_workspace_color').className;

	var vetor = document.getElementsByTagName('td');
	for(i = 0 ; i < vetor.length ; i++) {
		if (vetor[i].id == 'ws_class') {
			vetor[i].className = vetor[i].className.replace(oldColor, newColor);

		}
	}
	var vetor = document.getElementsByTagName('a');
	for(i = 0 ; i < vetor.length ; i++) {
		if (vetor[i].id == 'ws_class') {
			vetor[i].className = vetor[i].className.replace(oldColor, newColor);

		}
	}
	if(!findWorkspaceClass(newColor)) {
		addWorkspaceClass(newColor);
	}
	AjaxFunctions.updateWorkspaceStyle(idActive, newColor);
	trocaWorkspaceActiveColor(newColor);
}

function trocaWorkspaceActiveColor(color){
	var d = document.getElementById('active_workspace_color');
	d.className=color;
}

//function criaWorkspaceActiveId(color){
//	var div = document.createElement('div');
//	div.id = 'active_workspace_color-' + color;
//	return div;
//}

function isDiv(el) {
  return el.tagName == 'div' || el.tagName == 'DIV'
}


function findBlock(element) {
	var parent = element

	while (parent != null) {
		if (isDiv(parent) && parent.id != null && parent.id.length > 6 && parent.id.substring(0, 6) == 'block_') {
			return parent.id.substring(6)
		}
		parent = parent.parentNode
	}
	
	return null
}

function findWorkspaceClass(color) {
	var i;
	for(i = 0 ; i < document.styleSheets.length ; i++) {
		var href = document.styleSheets[i].href;
		if(href.indexOf('css-js/workspace_' + color + '.css') > -1) {
			return true;
		}
	}
	return false;
}

function addWorkspaceClass(color) {
	var cssNode = document.createElement('link');
	cssNode.setAttribute('rel', 'stylesheet');
	cssNode.setAttribute('type', 'text/css');
	cssNode.setAttribute('href', 'css-js/workspace_' + color + '.css');
	document.getElementsByTagName('head')[0].appendChild(cssNode);
}

function addClass(color) {
	var cssNode = document.createElement('link');
	cssNode.setAttribute('rel', 'stylesheet');
	cssNode.setAttribute('type', 'text/css');
	cssNode.setAttribute('href', 'css-js/block_' + color + '.css');
	document.getElementsByTagName('head')[0].appendChild(cssNode);
}

function findClass(color) {
	var i;
	for(i = 0 ; i < document.styleSheets.length ; i++) {
		var href = document.styleSheets[i].href;
		if(href.indexOf('css-js/blocks_' + color + '.css') > -1) {
			return true;
		}
	}
	return false;
}

function forceHide(nomeDiv, id) {
	var target = document.getElementById(nomeDiv + id);
	var other = document.getElementById('style_config_' + id);
	if(other != null && other.style.display == '') {
		other.style.display = 'none';
	}
	target.style.display = 'none';
}

function custom(nomeDiv, id) {
	var target = document.getElementById(nomeDiv + id);
	var other = document.getElementById('style_config_' + id);	
//	var block = document.getElementById('block_' + id);
	
	if(other != null && other.style.display == '') {
		other.style.display = 'none';
	}
	
	if(target.style.display == 'none') {
		target.style.display = '';
		target.style.zIndex = '10000';
	} else {
		target.style.display = 'none';
	}
}

function customForceHide(nomeDiv, outroDiv, id) {
	forceHide(outroDiv, id);
	custom(nomeDiv, id);
}

function renderCallback(content) {
	var i;
	var id = content[0];
	var html = content[1];
	var error = content[2];	
	var targetDiv;
	var sourceDiv;
	var holder = document.getElementById('hold_' + id);

	var divs = holder.getElementsByTagName('div');
	for( i = 0 ; i < divs.length ; i++) {
		var s = new String(divs[i].id);
		if(s.substring(0, 12) == 'content_div_') {
			targetDiv = divs[i];
		}
	}
	
	var temp = document.createElement('div');	
	if(html != '') {
		temp.innerHTML = html;
		var scripts = temp.getElementsByTagName('script');
		
		divs = temp.getElementsByTagName('div');
		for( i = 0 ; i < divs.length ; i++) {
			var s = new String(divs[i].id);
			if(s.substring(0, 12) == 'content_div_') {
				sourceDiv = divs[i];
			}
		}
		targetDiv.innerHTML = sourceDiv.innerHTML;
		for(i = 0 ; i < scripts.length ; i++) {
			eval(scripts[i].innerHTML);
		}
	}
}

function customApply(id) {
	var target = document.getElementById('custom_config_' + id);
	var content = document.getElementById('content_div_' + id);
	var keys = new Array();
	var values = new Array();
	var childs = target.getElementsByTagName('input');
	var selectedGroup = "";
	var i, j;
	j = 0;
	
	for(i = 0 ; i < childs.length; i++) {
		var node = childs[i];
		if(node.id != null && node.value != null) {
			if(node.id.indexOf('property_') > -1) {
				var key = node.id.replace('property_', '').replace('_' + id, '');
				var value = null
				if (node.type == 'text' || node.type == 'hidden') {
					value = node.value;
				} else if (node.type == 'checkbox') {
					if (node.checked) {
						value = true
					} else {
						value = false
					}
				}
				keys[j] = key;
				values[j] = value;
				j++;
			} else if (node.id == 'selectedGroup' && node.checked) {
				selectedGroup = node.value;
			}
		} 
	}
	
	childs = target.getElementsByTagName('select');
	for(i = 0 ; i < childs.length; i++) {
		var node = childs[i];
		if(node.id != null && node.value != null) {
			if(node.id.indexOf('property_') > -1 && node.value.replace(/ /g,'') != '') {
				var key = node.id.replace('property_', '').replace('_' + id, '');
				var value = node.value;
				keys[j] = key;
				values[j] = value;
				j++;
			}
		}
	}	
	
	if(keys.length > 0) {
		AjaxFunctions.applyCustom(id, keys, values, selectedGroup, renderCallback);
	}
	custom('custom_config_', id);
}

function setIntervalId(block, intervalId) {
	intervals["" + block] = intervalId;
}

function getIntervalId(block) {
	return intervals["" + block];
}

function refresh(block) {
	AjaxFunctions.render(block, renderCallback);
}

function startInterval(block, seconds) {
	var intId = getIntervalId(block);
	if(intId != null) {
		clearInterval(intId);
	}
	if(seconds > 0) {	
		var newIntId = setInterval('refresh(' + block + ')', seconds * 1000);
		setIntervalId(block, newIntId);
	}
}

function reOrderCallback() {
	document.location.href = document.location.href;
}

function reOrder(ws) {
	var width = window.innerWidth - 30;
	AjaxFunctions.reOrderBlocks(ws, width, reOrderCallback);
}

function newWorkspace() {
//	var span = document.getElementById('new_workspace');
	DesktopFunctions.addWorkspace(ownerId, 'Workspace', produto, addWorkspaceCallback);
//	addWorkspace();
//	span.innerHTML = newWsForm;
}

function addWorkspaceCallback(ret) {
	document.location.href = 'desktop.form?produto=' + produto + '&active=' + ret[2];
}

function rename(ws) {
	var active = document.getElementById('active_workspace');
	var color = document.getElementById('active_workspace_color').className;
	var nome = document.getElementById('active_workspace_nome').className;
	var temp = renameWsForm.replace(/#color/g, color).replace(/#nome/g, nome).replace(/#id/g, ws);
	active.innerHTML = temp;
}

function renameWorkspace(ws) {
	var active = document.getElementById('active_workspace');
	var color = document.getElementById('active_workspace_color').className;
	var nome = document.getElementById('active_workspace_nome').className;
	var novoNome = document.getElementById('submenu_input_' + ws).value;

	document.getElementById('active_workspace_nome').className = novoNome;
	AjaxFunctions.renameWorkspace(ws, novoNome);
	var temp = active.innerHTML.replace(color, color).replace(nome, novoNome);
	active.innerHTML = temp;
}

function deleteWorkspaceCallback(ret) {
	document.location.href = 'desktop.form?produto=' + produto + '&active=' + ret[2];
}

function deleteWorkspace(ws) {
	if(confirm('Os blocos deste Workspace serão perdidos! Deseja continuar?')) {
		DesktopFunctions.deleteWorkspace(ws, produto, deleteWorkspaceCallback);
	}
}

function createAuxiliaryDiv() {
	var div = document.createElement('div');
	div.id = 'curtain';

  	if (browser.isIE) {
		div.style.left= (document.documentElement.scrollLeft + document.body.scrollLeft) + 'px';
		div.style.top= (document.documentElement.scrollTop + document.body.scrollTop) + 'px';
		div.style.width = (document.body.clientWidth - 32) + 'px';
		div.style.height = (document.body.clientHeight - 32) + 'px';		
  	}
  
  	if (browser.isNS) {
		div.style.left= window.scrollX + 'px';
		div.style.top= window.scrollY + 'px';
		div.style.width = (window.innerWidth - 32) + 'px';
		div.style.height = (window.innerHeight - 32) + 'px';		
  	}

	div.style.position = 'absolute';
	div.onclick = new function() {
		var d = document.getElementById('curtain');
		if(d) {
			document.body.removeChild(d);
			delete(d);
		}
	}
	return div;
}


function populateSecondSelect(sourceSelect, targetId, keyInSession) {
	var value = sourceSelect.value
	AjaxFunctions.getListFromProperty(value, keyInSession, function(response) { populateSecondSelectCallback(response, targetId) })
}

function populateSecondSelectCallback(list, targetId) {
	DWRUtil.removeAllOptions(targetId);
	DWRUtil.addOptions(targetId, [' '])
	DWRUtil.addOptions(targetId, list)
}


function removeChildren(obj){
  if(typeof(obj)=='string'){
    obj = document.getElementById(obj);
  }
  while(obj.firstChild!=null){
    obj.removeChild(obj.firstChild);
  }
  return false;
}


function trimString(s) {
	var l=0; var r=s.length -1;
	while(l < s.length && (s[l] == ' ' || s[l] == '\t' || s[l] == '\n') )
	{	l++; }
	while(r > l && (s[l] == ' ' || s[l] == '\t' || s[l] == '\n'))
	{	r--;	}
	return s.substring(l, r+1);
}

function confirmaRemocao(obj) {
	return confirm('Confirma a remoção do ítem ' + obj + '?')
}

